/*
 * @Author: zhangyujie
 * @Date:   2015-08-12 10:45:35
 * @Last Modified by:   zhangyujie
 * @Last Modified time: 2015-08-14 16:18:53
 */

define(['jquery', 'd3','util','hammer'], function($, d3,util,Hammer) {
	function multicolorBrokenLine(capital,benefit,all,xAxis) {
		var setting = {
			selector: '#six',
			//xAxis: xAxis, /*['2011-1', '2011-2','2015-1','2015-2','2015-3','2016-1', '2016-5', '2018-1']*/
			xAxis: ['2011-1', '2011-2','2015-1','2015-2','2015-3','2016-1', '2016-5', '2018-1'],
			radius: 5,
           // series:data,
			series: [{
				name: '本期收益',
				color: '#7CE9F7',
				//data: capital/*[-5, -70, -8, -60, -9, -12, -3, -4]*/
				data: [-5, -70, -8, -60, -9, -12, -3, -4]
			}, {
				name: '累计收益',
				color: '#E4E950',
				//data: benefit/*[50, 10, 120, 11, 120, 13, 10, 5]*/
				data: [50, 10, 120, 11, 120, 13, 10, 5]
			}, {
				name: '本金+累计',
				color: '#65B2F9',
				//data: all/*[24, 80, 520, 110, 300, 1000, 50, 8]*/
				data: [24, 80, 520, 110, 300, 1000, 50, 8]
			}],
			legend: {
				title: {
					offset: {
						left: 90,
						top: 0
					},
					margin: {
						top: 30,
						left: 15
					},
					circle: {
						r: 6,
						cx: 0,
						cy: 0
					},
					text: {
						x: 10,
						y: 6,
						textStyle: {
							'font-size': "16px",
							'color': '#000'
						}
					}
				},
				total: {
					offset: {
						left: 65,
						top: 0
					},
					margin: {
						top: 80,
						left: 80
					},
					circle: {
						r: 6,
						cx: 0,
						cy: 0
					},
					text: {
						x: 10,
						y: 6,
						textStyle: {
							'font-size': "16px",
							'color': '#000'
						}
					}
				}
			},
			margin: {
				top: 110,
				right: 20,
				bottom: 25,
				left: 50
			}
		}
		six(setting)

		function six(setting) {

			var selector = setting.selector,
				series = setting.series,
				otherColor = setting.otherColor,
				legendSetting = setting.legend,
				colorset = setting.colorset,
				margin = setting.margin,
				relcontentW = document.querySelector(selector).offsetWidth,
				height = document.querySelector(selector).offsetHeight,
				length = series.length,
				dom = document.querySelector(selector)



			var svg,
				content,
				totalGroup,
				xScale,
				yScale,
				incomeGroup,
				circle,
				legend,
				titleGroup,
				totalGroup,
				xAxis,
				yAxis,
				xAxisData = setting.xAxis,
				yAxisData = [],
				yMax,
				diff

			if (xAxisData.length > 7) {
				var width = 1.5 * relcontentW
			} else {
				var width = relcontentW
			}

			var contentW = width - margin.left - margin.right
			var contentH = height - margin.top - margin.bottom

			yMax = d3.max(series[2]['data'], function(d) {
				return d
			})

			diff = yMax / 4
			for (var i = 0; i < yMax; i += diff) {
				yAxisData.push(Number(i.toFixed(0)))
			}
			yAxisData.push(yMax)
			xScale = d3.scale.ordinal()
				.domain(xAxisData)
				// .rangeRoundPoints([margin.left, width - margin.right])
				.rangeRoundPoints([0, contentW])
			yScale = d3.scale.linear()
				.domain([0, yMax])
				//.range([height - margin.bottom, margin.top])
				.range([contentH, 0])

			svg = d3.select(selector + " div").append('svg')
				.attr('width', width)
				.attr('height', height)
				.attr('class', "multicolor")

			var Ysvg = d3.select(selector).append('svg')
				.attr('width', width)
				.attr('height', height)

			legend = Ysvg.append('g')
				.attr('class', 'legend')


			titleGroup = legend.append('g')
				.attr('class', 'title')
				.attr('transform', 'translate(' + legendSetting['title']['margin']['left'] + ',' + legendSetting['title']['margin']['top'] + ')')
			totalGroup = legend.append('g')
				.attr('class', 'total')
				.attr('transform', 'translate(' + legendSetting['total']['margin']['left'] + ',' + legendSetting['total']['margin']['top'] + ')')

			for (var j = 0; j < length; j += 1) {
				titleGroup.append('circle')
					.attr('transform', 'translate(' + (j * legendSetting['title']['offset']['left']) + ',' + legendSetting['title']['offset']['top'] + ')')
					.attr('r', legendSetting['title']['circle']['r'])
					.attr('cx', legendSetting['title']['circle']['cx'])
					.attr('cy', legendSetting['title']['circle']['cy'])
					.attr('fill', series[j]['color'])
				titleGroup.append('text')
					.text(series[j]['name'])
					.attr('x', legendSetting['title']['text']['x'])
					.attr('y', legendSetting['title']['text']['y'])
					.attr('transform', 'translate(' + (j * legendSetting['title']['offset']['left']) + ',' + legendSetting['title']['offset']['top'] + ')')
					.style(legendSetting['title']['text']['textStyle'])

				totalGroup.append('circle')
					.attr('transform', 'translate(' + (j * legendSetting['total']['offset']['left']) + ',' + legendSetting['total']['offset']['top'] + ')')
					.attr('r', legendSetting['total']['circle']['r'])
					.attr('cx', legendSetting['total']['circle']['cx'])
					.attr('cy', legendSetting['total']['circle']['cy'])
					.attr('fill', series[j]['color'])

				totalGroup.append('text')
					.text(function() {
						//var text = j == length - 1 ? d3.sum(series[j]['data']) + '万' : d3.sum(series[j]['data'])
						return d3.sum(series[j]['data'])
					})
					.attr('x', legendSetting['total']['text']['x'])
					.attr('y', legendSetting['total']['text']['y'])
					.attr('transform', 'translate(' + (j * legendSetting['total']['offset']['left']) + ',' + legendSetting['total']['offset']['top'] + ')')
					.style(legendSetting['total']['text']['textStyle'])

			}
			totalGroup.append('text')
				.text("万")
				.attr('x', legendSetting['total']['text']['x'])
				.attr('y', legendSetting['total']['text']['y'])
				.attr('transform', 'translate(' + 180 + ',' + (legendSetting['total']['offset']['top'] -2)+ ')')
				.style(legendSetting['total']['text']['textStyle'])
			content = svg.append('g')
				.attr('class', 'content')
				.attr('transform', 'translate(10,' + margin.top + ')')

			Ycontent = Ysvg.append('g')
				.attr('class', 'content')
				.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')')
			xAxis = d3.svg.axis()
				.scale(xScale)
				.tickValues(xAxisData)
				.tickPadding(10)
				.orient('bottom')
				.tickSize(0)
			yAxis = d3.svg.axis()
				.scale(yScale)
				.tickValues(yAxisData)
				.tickPadding(10)
				.orient('left')
				.tickSize(0)

			content.append('g')
				.attr('class', 'xAxis')
				.attr('transform', 'translate(' + 0 + ',' + (contentH) + ')')
				.call(xAxis)


			Ycontent.append('g')
				.attr('class', 'yAxis')
				.attr('transform', 'translate(' + 0 + ',' + 0 + ')')
				.call(yAxis)

			Ycontent.selectAll('.yAxis .tick')
				.attr('opacity', function(d, i) {

					d3.select(this).append('line')
						.attr('x1', 0)
						.attr('y1', 0)
						.attr('x2', relcontentW - margin.left)
						.attr('y2', 0)

				})


			var area = d3.svg.area()
				.x(function(d, i) {
					return xScale(xAxisData[i])
				})
				.y0(contentH)
				.y1(function(d, i) {
					return yScale(d)
				});

			var valueline = d3.svg.line()
				.interpolate("linear")
				.x(function(d, i) {
					return xScale(xAxisData[i])
				})
				.y(function(d, i) {

					return yScale(d)
				})

			var brokeArea = content.append('g')
				.attr('class', 'brokeArea')



			for (var j = length - 1; j >= 0; j -= 1) {

				var brokeLinear = content.append('defs')
					.append('linearGradient')
					.attr('id', 'brokeArea' + j)
					.attr('x1', '100%')
					.attr('y1', '100%')
					.attr('x2', '100%')
					.attr('y2', '0%')

				brokeLinear.append('stop')
					.attr('offset', '0%')
					.style({
						'stop-color': '#DDEDFD',
						'stop-opacity': 0.5
					})

				brokeLinear.append('stop')
					.attr('offset', '100%')
					.style({
						'stop-color': series[j]['color'],
						'stop-opacity': 1
					})

				var pct = svg.select(".brokeArea")
					.append("g")
					.attr("class", "pct");
				pct.append("path")
					.datum(series[j]['data'])
					.attr("d", area)
					.style("fill", 'url(#brokeArea' + j + ')')

				brokeArea.append("path")
					.attr('class', 'line' + j)
					.attr('fill', 'none')
					.attr("stroke", series[j]['color'])
					.attr("stroke-width", 2)
					.attr("d", valueline(series[j]['data']))

				brokeArea.selectAll('.circle' + j)
					.data(series[j]['data'])
					.enter()
					.append('circle')
					.attr('class', 'circle' + j)
					.attr('r', setting.radius)
					.attr('cx', function(d, i) {
						return xScale(xAxisData[i])
					})
					.attr('cy', function(d, i) {
						return yScale(d)
					})
					.attr('fill', '#fff')
					.attr('stroke', '#84C6FF')
					.attr('stroke-width', 1)

			}

			var lineWrap = content.append('g')
				.style('display', 'none')
			var line = lineWrap
				.append('line')
				.attr('x1', 0)
				.attr('y2', 0)
				.attr('x2', 0)
				.attr('y2', height - margin.top - margin.bottom)
				.attr('fill', '#ffc10e')
				.attr('stroke', setting.series[0].color)
			var circleWrap = lineWrap.selectAll('.circle')
				.data([1, 2, 3])
				.enter()
				.append('g')

			circleWrap.append('circle')
				.attr('r', 8)
				.attr('fill', '#fff')
				.attr('stroke-width', '2px')
				.attr("class",function(d, i) {
					return "cir"+i
				})
				.attr('stroke', function(d, i) {

					return setting.series[i].color
				})

			circleWrap.append('circle')
				.attr('r', 4)
				.attr('fill', function(d, i) {

					return setting.series[i].color
				})
				.attr("class",function(d, i) {
					return "cir"+i
				})


				//console.log(content.selectAll(".circle0"))
			for (var j = 0; j < xAxisData.length; j++) {
				d3.select(svg.selectAll('.xAxis text')[j])
					.text(function() {
						for (var i = 0; i < xAxisData.length; i++) {

							$(this[i]).attr("data", i)

						}
					})
					
				d3.select(svg.selectAll('.circle0')[j])
					.text(function() {
						
						for (var i = 0; i < xAxisData.length; i++) {

							$(this[i]).attr("data", i)

						}
					})

				d3.select(svg.selectAll('.circle1')[j])
					.text(function() {
						for (var i = 0; i < xAxisData.length; i++) {

							$(this[i]).attr("data", i)

						}
					})

				d3.select(svg.selectAll('.circle2')[j])
					.text(function() {
						for (var i = 0; i < xAxisData.length; i++) {

							$(this[i]).attr("data", i)

						}
					})

			}
			content.selectAll(".xAxis text")
				.on('click', touch)
			svg.selectAll("circle")
				.on('click', touch)
				//.on('touchmove', touch)

			function touch() {
				console.log(111)
				var target = null,
					tagName, height,
					position, left, key,
					lineValue, rectValue,
					index, arr

				position = d3.mouse(dom)
				target = d3.event.target
				tagName = target.tagName

				left = position[0] - margin.left - parseInt($(".multicolor").css("margin-left"))

				
				if (left >= 0 ) {

					arr = getData(left, 0)

					var index = d3.select(this).attr("data")
					
					var cx = d3.select(svg.selectAll(".circle0")[0][index]).attr("cx")
					var cy = d3.select(svg.selectAll(".circle0")[0][index]).attr("cy")
					//var cx1 = d3.select(svg.selectAll(".circle1")[0][index]).attr("cx")
					var cy1 = d3.select(svg.selectAll(".circle1")[0][index]).attr("cy")
					//var cx2 = d3.select(svg.selectAll(".circle2")[0][index]).attr("cx")
					var cy2 = d3.select(svg.selectAll(".circle2")[0][index]).attr("cy")
					
					lineWrap.style('display', 'block')

					line
						.attr('transform', 'translate(' + cx + ',' + 0 + ')')

					circleWrap.selectAll(".cir0")
							.attr("cx",cx)
							.attr("cy",cy)
					circleWrap.selectAll(".cir1")
							.attr("cx",cx)
							.attr("cy",cy1)
					circleWrap.selectAll(".cir2")
							.attr("cx",cx)
							.attr("cy",cy2)
					

					var data0 = d3.select(svg.selectAll(".circle0")[0][index]).data()
					var data1 = d3.select(svg.selectAll(".circle1")[0][index]).data()
					var data2 = d3.select(svg.selectAll(".circle2")[0][index]).data()
					
					Ysvg.selectAll(".total text")[0][0].innerHTML = data0
					Ysvg.selectAll(".total text")[0][1].innerHTML = data1
					Ysvg.selectAll(".total text")[0][2].innerHTML = data2
				}

			}

			var hammertime = new Hammer(document.querySelector(".multicolor"));
			//添加事件
			var cur = 0

			var ulWidth = width

			var two_3 = $("#six_1").width()



			hammertime.on("pan", function(e) {


				cur += e.deltaX;

				if (cur * 0.2 > 0) {
					cur = 0;
					$(".multicolor").css("margin-left", 0)

					return
				}
				if (cur * 0.2 < -ulWidth + two_3) {
					cur = (-ulWidth + two_3) / 0.2

					$(".multicolor").css("margin-left", -ulWidth + two_3 + margin.left)

					return
				}

				$(".multicolor").css("margin-left", cur * 0.2)
			})

			function getData(num, index) {

				var xScaleData = setting.xAxis
				var unitData = contentW / (xScaleData.length - 1),
					preIndex,
					nextIndex, currentIndex, k,
					vaildIndex, y, currentValue, vaildValue, x, b,
					data = setting.series[index].data



				var currentIndex = Math.floor(num / unitData)

				if (currentIndex < 0) {

					currentIndex = 0
				}

				if (currentIndex > xScaleData.length - 1) {

					currentIndex = xScaleData.length - 1
				}

				vaildIndex = currentIndex + 1

				currentValue = yScale(data[currentIndex])

				vaildValue = yScale(data[vaildIndex])

				x = num - (currentIndex * unitData)

				k = 1

				b = currentValue

				y = k * (vaildValue - currentValue) * x / unitData + b

				return [currentIndex, y]
			}

		}
	}

	return {
		multicolorBrokenLine: multicolorBrokenLine
	}

})